<?php

namespace Frieza\Modules\Position\Actions;

use Doraemon\cache\BlackList;
use Doraemon\model\AdmUserType;
use Doraemon\service\admin\AdmUserFilter;
use Doraemon\service\CommonEmblem;
use Doraemon\service\search\AdmUserSearch;
use Doraemon\service\User;
use Encore\Admin\Actions\RowAction;
use Encore\Admin\Facades\Admin;
use Illuminate\Http\Request;
use Doraemon\model\BestUser;
use Doraemon\model\AdmRecommendUser;
use Doraemon\model\Member;
use Illuminate\Support\MessageBag;
use Doraemon\cache\Queue;
use Doraemon\cache\SolrUpdateCollector;
use Doraemon\cache\EsUpdateCollector;
use Doraemon\service\solr\SolrUserMark;
use Doraemon\model\AdmToBeMarked;
use Doraemon\model\AdmOperateLog;
use Doraemon\service\Themis\Log as ThemisLog;
use Doraemon\model\Themis\Log as ThemisLogModel;

class OperateLogo extends RowAction
{
    public $name = '运营标识';
    const AUTH_TAG = [
        AdmUserType::AUTH_TAG_NO => '无',
        AdmUserType::AUTH_TAG_SUSPECT_BUSINESS => '疑似商业用户',
        AdmUserType::AUTH_TAG_TO_BRAND => '待认证品牌',
    ];
    const QUALITY = [
        AdmUserType::NORMAL => '未标识状态',
        AdmUserType::B3 => 'B3(普通网图+运营灰名单)',
        AdmUserType::B2 => 'B2(商业灰名单)',
        AdmUserType::B1 => 'B1(黑名单)',
        AdmUserType::XL => 'XL'
    ];

    public static $user_quality = ['good' => 1, 'normal' => 2, 'S2' => 3, 'B2' => 9, 'B1' => 10, 'B3' => 11];

    public function handle($uid,Request $request)
    {
        $auth_tag = $request->get('auth_tag');
        $identity_mark = $request->get('identity_mark');
        $quality = $request->get('quality_mark');
        $remark = $request->get('remark');


        //获取运营级用户质量
        $qualityOld = (int)self::getUserQuality($uid);
        $userTypeOld = AdmUserType::getByUid($uid);
        //获取已存在的标签信息
        $identity_markOld = $userTypeOld['identity_mark'];

        $imark = explode(',', $identity_mark);
        $imark = array_filter($imark);
        foreach ($imark as $_k => $_v) {
            $imark[$_k] = trim($_v);
        }
        $imarkForData = implode(',', $imark);
        $imarkForSolr['identity_mark'] = implode(' ', $imark);
        $update_data = [
            'auth_tag' => $auth_tag,
            'quality' => $quality,
            'remark' => $remark,
            'addtime' => time(),
            'identity_mark' => $identity_mark,
            'admin_id'=> Admin::user()->id,
        ];
        // 禁止私信 themis日志
        if (strpos($identity_mark, "工厂店")) {
            // 添加themis日志
            $aOpt = array(
                'admin_id'    => Admin::user()->id,
                'remark'      => "账号已被禁止私信",
                'status'      => ThemisLogModel::STATUS_STOP_SAYING,
                'action_type' => ThemisLogModel::ACTION_TYPE_ADD_STOP_SAYING,
                'illegal_or_punish' => ThemisLogModel::ACTION_PUNISH,
            );
            $aThemisLog = ThemisLog::fetchThemisLogData($uid, $aOpt);
            ThemisLog::add($aThemisLog);
        }
        if (strpos($identity_markOld, "工厂店")) {
            if (false === strpos($identity_mark, "工厂店")) {
                // 添加themis日志
                $aOpt = array(
                    'admin_id'    => Admin::user()->id,
                    'remark'      => "账号已解除私信限制",
                    'status'      => ThemisLogModel::STATUS_STOP_SAYING,
                    'action_type' => ThemisLogModel::ACTION_TYPE_DEL_STOP_SAYING,
                    'illegal_or_punish' => ThemisLogModel::ACTION_PUNISH,
                );
                $aThemisLog = ThemisLog::fetchThemisLogData($uid, $aOpt);
                ThemisLog::add($aThemisLog);
            }
        }
        // B1 B2 B3 themis日志
        if (in_array($quality, [AdmUserType::B3, AdmUserType::B2, AdmUserType::B1])) {
            if (AdmUserType::B1 == $quality) {
                $iActionType = ThemisLogModel::ACTION_TYPE_ADD_B1;
            } else if (AdmUserType::B2 == $quality) {
                $iActionType = ThemisLogModel::ACTION_TYPE_ADD_B2;
            } else if (AdmUserType::B3 == $quality) {
                $iActionType = ThemisLogModel::ACTION_TYPE_ADD_B3;
            }
            // 添加themis日志
            $aOpt = array(
                'admin_id' => Admin::user()->id,
                'remark' => "该用户账号已被列为" . self::QUALITY[$quality],
                //'status'      => ThemisLogModel::STATUS_STOP_SAYING,
                'action_type' => $iActionType,
                'illegal_or_punish' => ThemisLogModel::ACTION_PUNISH,
            );
            $aThemisLog = ThemisLog::fetchThemisLogData($uid, $aOpt);
            ThemisLog::add($aThemisLog);
        }
        if (in_array($qualityOld, [AdmUserType::B3, AdmUserType::B2, AdmUserType::B1])) {
            if (AdmUserType::NORMAL == $quality) {
                if (AdmUserType::B1 == $quality) {
                    $iActionType = ThemisLogModel::ACTION_TYPE_DEL_B1;
                } else if (AdmUserType::B2 == $quality) {
                    $iActionType = ThemisLogModel::ACTION_TYPE_DEL_B2;
                } else if (AdmUserType::B3 == $quality) {
                    $iActionType = ThemisLogModel::ACTION_TYPE_DEL_B3;
                }
                // 添加themis日志
                $aOpt = array(
                    'admin_id' => Admin::user()->id,
                    'remark' => "该用户账号已被解除" . self::QUALITY[$quality],
                    //'status'      => ThemisLogModel::STATUS_STOP_SAYING,
                    'action_type' => $iActionType,
                    'illegal_or_punish' => ThemisLogModel::ACTION_PUNISH,
                );
                $aThemisLog = ThemisLog::fetchThemisLogData($uid, $aOpt);
                ThemisLog::add($aThemisLog);
            }
        }
        //处理优质用户的相关逻辑
        if (!in_array($qualityOld, [false, 3])){
            if ($qualityOld != $quality){
                // 更新|删除老的用户质量数据
                if ($qualityOld == self::$user_quality['S2']){
                    $judge = self::delBestUser($uid);
                    if ($judge) {
                        $rs = AdmUserType::updateInfo($uid,$update_data);
                    }
                }elseif (in_array($qualityOld, [self::$user_quality['B1'], self::$user_quality['B2'], self::$user_quality['B3'], self::$user_quality['normal'], self::$user_quality['good']])){
                    $rs = AdmUserType::updateInfo($uid,$update_data);
                }
                if (!$rs) {
                    return $this->response()->error('操作失败!!');
                }
            }else{
                $rs = AdmUserType::updateInfo($uid,$update_data);
            }
        }else{
            $rs = AdmUserType::getByUid($uid);
            if ($rs){
                $rs = AdmUserType::updateInfo($uid,$update_data);
            }else{
                $user_addtime = Member::getOne($uid)['addtime'];
                $update_data['addtime'] = $user_addtime;
                $rs = AdmUserType::save($uid,$update_data);
            }
        }

        Queue::insertQueue('Photo/reindex_photo_solr', array(
            'uid' => $uid,
        ), Queue::QUEUE_COMMON);
        SolrUpdateCollector::insert($uid);
        EsUpdateCollector::insert($uid);
        if (empty($rs)){
            return $this->response()->error('出错啦,稍后重试!!');
        }else{
            SolrUserMark::updateUserMark($uid,$imarkForSolr);
            if ($quality && $quality == self::$user_quality['B1']){
                BlackList::addUid2BlackList($uid);
                //B1用户内容更新 事件化实现
//                Queue::insertQueue('UserB1/setStatusByUid', array(
//                    'uid' => $uid,
//                    "type"=>"set_b1"
//                ), Queue::QUEUE_COMMON);
            }

            if (($quality && $quality != self::$user_quality['B1']) || $quality == AdmUserType::NORMAL){
                BlackList::delUid4BlackList($uid);
                //取消B1内容更新  事件化实现
//                Queue::insertQueue('UserB1/setStatusByUid', array(
//                    'uid' => $uid,
//                    "type"=>"cancel_b1"
//                ), Queue::QUEUE_COMMON);
            }

            if ($quality && $quality == self::$user_quality['B2']) {
                BlackList::addUid2B2List($uid);
            }

            if (($quality && $quality != self::$user_quality['B2']) || $quality == AdmUserType::NORMAL){
                BlackList::delUid4B2List($uid);
            }
        }

        if ($auth_tag || $quality || $remark  || $identity_mark) {
            AdmToBeMarked::deleteByUid($uid);
        }

        if ($identity_mark){
            Queue::insertQueue('DataUserProfile/update', array(
                'uid' => $uid,
                'param_json' => json_encode(array(
                    "adm_tag" => $imarkForSolr['identity_mark'],
                )),
            ), Queue::QUEUE_STAT);
            $identity_mark = trim($identity_mark);
            // 检查当前标签中是否有"官方账号"、"官方帐号"字样，如果有该标签，而且/home/adm_rsync_dir/not_show_fans.uid文件中没有当前的uid，则往文件中写入uid
            if (strpos($identity_mark, '官方账号') !== false || strpos($identity_mark, '官方帐号') !== false) {
                // 获取不显示粉丝数的所有uid
                $not_show_fans_uid = User::getNotShowFans();
                $uid = trim($uid);

                if (empty($not_show_fans_uid[$uid])) {
                    User::addNotShowFansUid($uid);
                }
            }
            CommonEmblem::resetExpertEmblem($uid);
        }
        AdmUserFilter::updateUserQuality($uid);
        AdmUserSearch::updateAdmUserSearchByUid($uid);
        $admin_id = Admin::user()->id;
        $admin_name = Admin::user()->username;
        AdmOperateLog::addLog($uid,AdmOperateLog::$operate_type['edit_user_quality'],$admin_id,$admin_name,$qualityOld,$quality);
        return $this->response()->success('操作成功')->refresh();

    }

    public function retrieveModel(Request $request)
    {
        if (!$key = $request->get('_key')) {
            return false;
        }

        return $key;
    }

    public function form($request)
    {
        $uid = $request->uid;
        //获取该用户的后台标识信息
        $adm_user_info = AdmUserType::getById($uid);
        //dd($adm_user_info);
        //获取该用户的用户标识
        $user_auth_tag = $adm_user_info['auth_tag'];
        if ($user_auth_tag == 127){
            $user_auth_tag = AdmUserType::AUTH_TAG_NO;
        }
        //获取该用户的标签
        $user_identity_mark = $adm_user_info['identity_mark'];
        //获取该用户的用户备注
        $user_remark = $adm_user_info['remark'];
        //获取该用户的质量等级
        $user_quality = $adm_user_info['quality'];
        $this->radio('auth_tag', '用户标识')->options(self::AUTH_TAG)->default($user_auth_tag);
        $this->text('identity_mark', '标签')->rules()->default($user_identity_mark);
        $this->radio('quality_mark', '质量等级')->options(self::QUALITY)->default($user_quality);
        $this->textarea('remark', '备注')->default($user_remark);
    }


    //获取运营标识信息
    private static function getUserQuality($uid){
        if (BestUser::checkBest($uid)){
            return self::$user_quality['S2'];
        }
        //是否在灰(B2)，黑名单(B1)里
        $qualityOld = AdmUserType::getByUid($uid);
        if ($qualityOld) {
            return $qualityOld['quality'];
        } else {
            return false;
        }
    }

    //移除用户S2信息
    private static function delBestUser($uid){
        // 删除用户在推荐表的数据
        AdmRecommendUser::deleteByUid($uid);
        // 删除精华表数据
        BestUser::deleteUser($uid);
        return true;
    }

}
